package com.nl.controller.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nl.controller.common.util.MD5;
import com.nl.controller.web.service.MeteorologicalStateChangeService;
import com.nl.controller.web.service.SmsInterfacesService;
import com.nl.controller.web.service.SmsQuerySentService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @desc 沛县气象局接口
 * @return null
 * @author ll
 * @date 2020/11/16 14:28
 */
@RestController
@Slf4j
@RequestMapping("pxQxjInterface")
public class SmsPxQxjController {
    @Autowired
    private SmsInterfacesService smsInterfacesService;

    @Autowired
    private SmsQuerySentService smsQuerySentService;

    @Autowired
    private MeteorologicalStateChangeService meteorologicalStateChangeService;

    //鉴权盐值
    public static String KEY = "yjfbzx";
    /**
     * @desc 沛县气象局任务同步接口
     * @param request 
     * @return java.util.Map<java.lang.String,java.lang.Object>
     * @author ll
     * @date 2020/11/16 14:29
     */
    @RequestMapping(value = "/sendTaskDetailSyn")
    public Map<String, Object> sendTaskDetailSyn(
            //@RequestParam(value = "taskDetailSynReq", required = true) String taskDetailSynReq
            HttpServletRequest request){
		/*Map<String, Object> map = smsInterfacesService.taskDetailSyn(taskDetailSynReq);
		log.info("【任务信息同步接口】返回数据：{}", map);
		return map;*/

        InputStream in;
        String reqJson="";
        String timeStamp = "";
        Map<String, Object> map = new HashMap<>();
        try {
            in = request.getInputStream();
            reqJson = IOUtils.toString(in, "utf-8");
            log.info("sendTaskDetailSyn:"+reqJson);
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.toString());
        }
        boolean authResult = this.getAuthentication(reqJson,KEY);

        if(authResult){
            map = smsInterfacesService.taskDetailSyn(reqJson);
        }else{
            map.put("resultCode","-1");
            map.put("resultDesc","接口鉴权失败");
        }

        log.info("【沛县气象局任务同步】返回数据：{}", map);
        return map;
    }

    /**
     * @desc 沛县气象局发送量查询接口
     * @param request
     * @return com.alibaba.fastjson.JSON
     * @author ll
     * @date 2020/11/16 18:15
     */
    @PostMapping("sendDetailQry")
    public JSON sendDetailQry(
            HttpServletRequest request
            //@RequestParam(value = "taskId", required = true)String taskId
    ){
        InputStream in;
        String reqJson="";
        JSONObject json2= new JSONObject();
        try {
            in = request.getInputStream();
            reqJson = IOUtils.toString(in, "utf-8");
            if (null == reqJson || "".equals(reqJson)) {
                json2.put("resultCode", "-1");
                json2.put("resultDesc", "失败");
                return json2;
            }
            JSONObject jsonObject = JSONObject.parseObject(reqJson);
            String taskId = jsonObject.getString("taskId");
            log.info("沛县气象局发送量查询接口入参:"+reqJson);

            boolean authResult = this.getAuthentication(reqJson,KEY);

            if(authResult){
                json2 = smsQuerySentService.querySentInfo(taskId);
            }else{
                json2.put("resultCode","-1");
                json2.put("resultDesc","接口鉴权失败");
            }

        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.toString());
        }
//		log.info(taskId);
//		if (null == taskId || "".equals(taskId)) {
//			json2.put("resultCode", "-1");
//			json2.put("resultDesc", "失败");
//			return json2;
//		}
//		json2 = smsQuerySentService.querySentInfo(taskId);
        log.info("沛县气象局发送量查询接口回参:"+json2);
        return json2;

    }

    /**
     * @desc 沛县气象局任务状态变更
     * @param request 
     * @return java.util.Map<java.lang.String,java.lang.Object>
     * @author ll
     * @date 2020/11/16 18:16
     */
    @RequestMapping(value = "/taskStatusChange")
    public Map<String, Object> meteorologicalStatestateChange(
            //@RequestParam(value = "stateChangeList", required = true) String stateChangeList){
            HttpServletRequest request
    ){
        InputStream in;
        String reqJson="";
        Map<String, Object> map = new HashMap<>();
        try {
            in = request.getInputStream();
            reqJson = IOUtils.toString(in, "utf-8");
            log.info("stateChangeList:"+reqJson);
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.toString());
        }

        log.info("沛县气象局任务状态变更接口入参:"+reqJson);

        boolean authResult = this.getAuthentication(reqJson,KEY);

        if(authResult){
            map = meteorologicalStateChangeService.meteorologicalStateChange(reqJson/*stateChangeList*/);
        }else{
            map.put("resultCode","-1");
            map.put("resultDesc","接口鉴权失败");
        }
        log.info("【气象局项目状态变更接口】返回数据：{}", map);
        return map;
    }


    /**
     * @desc 鉴权判断
     * @param reqJson 
     * @return boolean
     * @author ll
     * @date 2020/11/16 14:41
     */
    public  boolean getAuthentication(String reqJson,String key){
        
        boolean result = false;

        String timeStamp = "";
        String cityId = "";
        String token = "";
        JSONObject json = JSON.parseObject(reqJson);
        timeStamp = json.getString("timeStamp");
        cityId = json.getString("cityId");
        token = json.getString("token");
        MD5 md5 = new MD5();
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
            Date now = new Date();
            Date requestDate = format.parse(timeStamp);
            //180000 三分钟以内有效
            if (now.getTime() - requestDate.getTime()<180000 && now.getTime() - requestDate.getTime()>0) {
                log.info(now.getTime() - requestDate.getTime()+"");
                String nowToken = md5.getMD5ofStr(cityId+timeStamp+key);
                if (token.equals(nowToken)) {
                    log.info("鉴权通过");
                    result = true;
                }else{
                    log.info("鉴权失败");
                }
            }
        } catch (ParseException e) {
            log.error("鉴权发生异常:"+e.toString());
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) {
        MD5 md5 = new MD5();
        System.out.println(md5.getMD5ofStr("1620201117110700yjfbzx"));
    }
}
